﻿using System;
using CzfSDK;
using System.Collections.Generic;

namespace Server
{
	public class RoomWait
	{
		public Room room = null;
		public object room_lock = new object();
		public int waitCount; // 房间开始需要的人数
		public int npcCount;  // 房间中的NPC人数
		public string type;


		public RoomWait(int waitCount, int npcCount, string type)
		{
			this.waitCount = waitCount;
			this.npcCount = npcCount;
			this.type = type;
		}

		public string WaitRoom(User user)
		{
			lock (room_lock) {
				if (room == null) {
					room = RoomManager.CreateRoom (waitCount, npcCount, type, this);
				}

				room.UserIn (user);
			}
			return "OK";
		}

		public string StopWaitRoom(User user)
		{
			lock (room_lock) {
				if (room == null) {
					throw new CzfProtoException (Constants.ERR3, "当前没有在匹配中");
				}

				if(!room.users.Contains(user))
					throw new CzfProtoException (Constants.ERR3, "当前没有在匹配中.");

				room.UserOut (user);
			}
			return "OK";
		}
	}


	public static class RoomManager
	{
		public const string TYPE_Guide = "guide";
		public const string TYPE_1Single = "1Single";
		public const string TYPE_1V1 = "1v1";
		public const string TYPE_2V2 = "2v2";

		private static int roomId = 0;
		private static object room_lock = new object();

		private static Dictionary<string, RoomWait> allWait = new Dictionary<string, RoomWait>();

		public static void Init()
		{
		}

		static RoomManager()
		{
			CzfLog.Info("初始化竞技场");
			allWait ["1v1"] = new RoomWait (2, 0, TYPE_1V1);
			allWait ["2v2"] = new RoomWait (4, 0, TYPE_2V2);
			allWait ["1Single"] = new RoomWait (2, 1, TYPE_1Single);
			allWait ["guide"] = new RoomWait (2, 1, TYPE_Guide);
			CzfLog.Info("初始化竞技场完成");
		}

		public static string WaitRoom(User user, string type)
		{
			if (!allWait.ContainsKey (type))
				throw new CzfProtoException (Constants.ERR3, "没有这个类型:" + type);

			var roomWait = allWait [type];
			return roomWait.WaitRoom(user);
		}

		public static string StopWaitRoom(User user, string type)
		{
			if (!allWait.ContainsKey (type))
				throw new CzfProtoException (Constants.ERR3, "没有这个类型:" + type);

			var roomWait = allWait [type];
			return roomWait.StopWaitRoom(user);
		}

		/// <summary>
		/// 创建一个房间
		/// </summary>
		/// <returns>The room.</returns>
		/// <param name="WaitCount">Wait count.</param>
		/// <param name="npcCount">Npc count.</param>
		public static Room CreateRoom(int waitCount, int npcCount, string type, RoomWait wait)
		{
			lock (room_lock) {
				roomId++;
				var room = new Room (roomId.ToString (), waitCount, npcCount, type, wait);
				return room;
			}

		}
	}
}

